package notes.java.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 模拟 5000个请求，并发量200，进行计算，并发正常结果5000，异常不等于5000
 * @author wangcs
 *
 */
public class U12_TestReentrantLock {

	// 5000个请求
	private static int reqNum = 5000;
	// 并发200
	private static int permits = 200;
	
	// 计数器
	private static int count = 0;
	
	// Lock
	private static Lock reentrantLock = new ReentrantLock();
	
	public static void main(String[] args) throws Exception{
		ExecutorService executor = Executors.newCachedThreadPool();
		
		// 信号量，控制并发数
		Semaphore semaphore = new Semaphore(permits);
		// 线程计数
		CountDownLatch latch = new CountDownLatch(reqNum);
		for (int i = 0; i < reqNum; i++) {
			executor.execute(()->{
				try {
					semaphore.acquire();
					latch.countDown();
					add();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				semaphore.release();
			});
		}
		// 等待所有线程执行完
		latch.await();
		System.out.println(count);
		executor.shutdown();
	}
	
	private static void add() {
		// 加锁
		reentrantLock.lock();
		try {
			count++;
		} finally {
			// 释放锁
			reentrantLock.unlock();
		}
	}
}
